package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class TemplateServiceImpl implements ITemplateService {

    // 注入freemarker配置
    @Autowired
    private Configuration configuration; // 静态实例

    @Autowired
    private MinIOService minIOService; // 文件上传下载云服务

    @Autowired
    private IApArticleService articleService; // 文章信息表，存储已发布的文章 服务类

    @Autowired
    ApArticleSearchRepository searchRepository; // es的仓库接口


    /**
     *保存文章自动生成静态页面
     * @param article
     * @param content
     */
    @Override
    @Async // 异步调用
    public void createHtml(ApArticle article, String content) {
        try {
            System.out.println(Thread.currentThread().getName() + "生成静态html服务开始执行");
            //1. 根据配置找到对应的模板
            Template template = configuration.getTemplate("article.ftl");
            //2. 封装数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //3. 合并模板数据
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            //4. 上传静态html文件到minio
            InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String url = minIOService.upload(article.getId() + ".html", is, "text/html");
            //5. 将url 地址更新到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);

            // 将数据同步到es 中
            // 创建 es 文章信息表对象
            ApArticleSearch search = new ApArticleSearch();
            // 进行数据copy
            BeanUtils.copyProperties(article, search);
            //仓库接口进行同步数据到es
            searchRepository.save(search);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
